#!/usr/bin/env python
from google.appengine.ext import db
import LectureM

def getQuestionByLecture(lecture):
    questions = db.Query(Question).filter('lecture =', lecture).filter('deleted =',False).order('index')
    return questions

def resetQuestions(lectureKey):
    owner = GeneralM.getEmail()
    lecture = LectureM.getLectureByKey(lectureKey)
    if not lecture:
        return 'error: lecture not found'
    elif not owner:
        return 'error: user is not logged in'
    else:
        db.delete(db.Query(Question).filter('lecture =', lecture).fetch(limit=1000))
        return 'success'

def addQuestion(name, answers, rightAnswer, lectureKey, index):
    owner = GeneralM.getEmail()
    name = name.strip()
    lecture = LectureM.getLectureByKey(lectureKey)
    if not lecture:
        return 'error: lecture not found'
    elif not owner:
        return 'error: user is not logged in'
    elif name == '':
        return 'error: Question cannot be empty'
    elif db.Query(Question).filter('name =', name).filter('lecture =', lecture).count() > 0:
        return 'error: Question already exists'
    elif answers is None:
        return 'error: No answers submitted'
    else:
        question = Question(name = name, answers=answers, rightAnswer=rightAnswer, lecture = lecture, index = index)
        question.put()
        return question

def getQuestionName(questionKey):
    question=Question.get(questionKey)
    return question.answers

def getQuestionByKey(key):
    if key:
        question = Question.get(key)
        return question
    else:
        return None
   
def getQuestionAnswers(questionKey):
    owner = GeneralM.getEmail()
    if questionKey:
        question=Question.get(questionKey)
        if CourseM.isOwner(question.lecture.course):
            return question.answers
   
class Question(db.Model):
    lecture = db.ReferenceProperty(LectureM.Lecture)
    index= db.IntegerProperty()
    name = db.StringProperty()
    answers = db.ListProperty(str, default=[])
    rightAnswer=db.IntegerProperty()
    deleted=db.BooleanProperty(default=False)
    
import GeneralM
import CourseM